const express = require('express')
const bodyParser = require('body-parser')
const UserService = require('./user-service.js')
const BooksService = require('./books-server.js')
const session = require('express-session')
const app = express()
// 给app配置bodyParser中间件
// 通过如下配置再路由种处理request时，可以直接获得post请求的body部分
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
//允许跨域
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
  )
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  if (req.method === 'OPTIONS') {
    res.send(200)
  } else {
    next()
  }
})

//添加 session 功能
app.use(
  session({
    name: 'identityKey',
    secret: 'adsfadsfqurewoiu',
    resave: false,
    saveUninitialized: true,
    cookie: { path: '/', maxAge: 30 * 60 * 1000 },
    rolling: true
  })
)

// 注册路由
const router = express.Router()
// 路由中间件
router.use((req, res, next) => {
  // 任何路由信息都会执行这里面的语句
  console.log('this is a api request!')
  // 把它交给下一个中间件，注意中间件的注册顺序是按序执行
  next()
})

//获取用户列表信息的路由
//登录
router.post('/login', UserService.login)
//注册
router.post('/register', UserService.register)
//注销
router.post('/logout', UserService.logout)

//书籍获取及状态改变路由
//书籍上传
router.post('/bookupload', BooksService.bookupload)
//书籍收藏
router.post('/bookcollect', BooksService.bookcollect)
//取消收藏
router.post('/bookcancelcollect', BooksService.bookcancelcollect)
//书籍借阅
router.post('/bookborrow', BooksService.bookborrow)
//书籍归还
router.post('/bookcancelborrow', BooksService.bookcancelborrow)
//书籍删除
router.post('/bookdelete', BooksService.bookdelete)
//获取书籍(id,关键字)
router.post('/bookslist', BooksService.bookslist)
// //按类型获取书籍列表
// router.post('/classifybookslist', BooksService.adminbooks)
//获取管理书籍
router.post('/adminbookslist', BooksService.adminbookslist)
//获取我的书籍列表
router.post('/mybookslist', BooksService.mybookslist)
//管理书籍状态
router.post('/adminbooks', BooksService.adminbooks)

// 所有的路由会加上“／api”前缀
app.use('/api', router) //添加router中间件

// express 自动帮我们创建一个server，封装的node底层http
app.listen(3003, () => {
  console.log('node server is listening 3003')
})
